import express from 'express';
import * as articles from '../../controllers/articles.js';
import * as categories from '../../controllers/categories.js';
import * as comments from '../../controllers/comments.js';
// 引入JWT验证中间件
import { auth } from '../../auth/auth.js';

const router = express.Router();

// 15. 获取统计数据 (总体数据)
router.get('/info', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/data/info 请求...');
    
    // 获取文章总数
    const [articleCountResult] = await articles.selectArticlesCount();
    console.log('文章总数查询结果:', articleCountResult);
    const totalArticle = articleCountResult.count || 0;
    
    // 获取评论总数
    const [commentCountResult] = await comments.selectCommentsCount();
    console.log('评论总数查询结果:', commentCountResult);
    const totalComment = commentCountResult.count || 0;
    
    // 获取今日文章数和今日评论数
    const today = new Date().toISOString().split('T')[0]; // 格式：2025-01-15
    const [todayArticleResult] = await articles.selectTodayArticlesCount(today);
    const dayArticle = todayArticleResult.count || 0;
    const [todayCommentResult] = await comments.selectTodayCommentsCount(today);
    const dayComment = todayCommentResult.count || 0;
    
    console.log('统计数据汇总:', {
      totalArticle,
      dayArticle,
      totalComment,
      dayComment
    });
    
    res.send({
      code: 200,
      msg: "获取成功",
      data: {
        totalArticle,
        dayArticle,
        totalComment,
        dayComment
      }
    });
  } catch (error) {
    console.error('获取数据统计失败:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).send({
      code: 500,
      msg: "获取失败"
    });
  }
});

// 16. 日新增文章数量统计 (近一周)
router.get('/article', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/data/article 请求...');
    // 获取最近7天的文章发布数据
    const lastWeekData = [];
    const today = new Date();
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      const [dayData] = await articles.selectArticlesByDate(dateStr);
      lastWeekData.push({
        date: dateStr,
        count: dayData.count || 0
      });
    }
    res.send({
      code: 200,
      msg: "获取成功",
      data: lastWeekData
    });
  } catch (error) {
    console.error('获取文章数据统计失败:', error);
    res.status(500).send({
      code: 500,
      msg: "获取失败"
    });
  }
});

// 17. 各类型文章数量统计
router.get('/category', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/data/category 请求...');
    // 获取每个分类的文章数量
    const categoryData = await categories.selectCategoryArticleCount();
    res.send({
      code: 200,
      msg: "获取成功",
      data: categoryData.map(item => ({
        name: item.name,
        articles: item.articleCount || 0
      }))
    });
  } catch (error) {
    console.error('获取分类数据统计失败:', error);
    res.status(500).send({
      code: 500,
      msg: "获取失败"
    });
  }
});

// 18. 日文章访问量  (近一周)
router.get('/visit', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/data/visit 请求...');
    // 构建访问数据对象（实际项目中需要实现访问统计功能）
    const visitData = {};
    const today = new Date();
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      const dateStr = date.toISOString().split('T')[0];
      // 模拟数据
      visitData[dateStr] = Math.floor(Math.random() * 1000) + 500;
    }
    res.send({
      code: 200,
      msg: "获取成功",
      data: visitData
    });
  } catch (error) {
    console.error('获取访问数据统计失败:', error);
    res.status(500).send({
      code: 500,
      msg: "获取失败"
    });
  }
});

export default router;
